//
//  VoicePlayerViewController.m
//  TestApplication
//
//  Created by Hanlingyu on 16/9/23.
//  Copyright © 2016年 ltq. All rights reserved.
//

#import "VoicePlayerViewController.h"
#import "UIImageView+WebCache.h"
#import "HomeChannelDetailModel.h"
#import "HomeChannelDetailContent.h"
#import "TAMacro.h"
#import "VoicePlayerRotatingView.h"
#import "ChannelVoice.h"
#import "NSString+Time.h"
#import <AVFoundation/AVFoundation.h>
@interface VoicePlayerViewController ()

@property (nonatomic, assign) CGFloat totalTime;

@property (nonatomic, copy) NSString *currentUrl;
@property (weak, nonatomic) IBOutlet UIButton *backButton;
@property (weak, nonatomic) IBOutlet UIImageView *backImageView;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (nonatomic, strong) VoicePlayerRotatingView *rotatingView;
@property (weak, nonatomic) IBOutlet UISlider *slider;
@property (nonatomic, strong) AVPlayer *player;
@property (weak, nonatomic) IBOutlet UIButton *nextButton;
@property (weak, nonatomic) IBOutlet UIButton *pauseButton;

@property (weak, nonatomic) IBOutlet UIButton *lastButton;

@property (weak, nonatomic) IBOutlet UILabel *playingTimeLabel;

@property (weak, nonatomic) IBOutlet UILabel *maxTimeLabel;



@property (nonatomic, strong) id playTimeObserver;

@property (nonatomic, assign) BOOL isPlaying;

@end

static VoicePlayerViewController *audioVC;
@implementation VoicePlayerViewController
{
    AVPlayerItem *playerItem;

}

+(VoicePlayerViewController *)createPlayerController{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        audioVC = [[VoicePlayerViewController alloc] init];
        audioVC.view.backgroundColor = [UIColor whiteColor];
        audioVC.player = [[AVPlayer alloc]init];
        //后台播放
        AVAudioSession *session = [AVAudioSession sharedInstance];
        [session setActive:YES error:nil];
        [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    });
    return audioVC;
}

- (void)setDetailModel:(HomeChannelDetailModel *)detailModel {
    _detailModel = detailModel;
    if ([_detailModel.content.voice.url isEqualToString:_currentUrl]) {

        NSLog(@"相同曲目");
    } else {
        
        // 如果已经存在 移除通知、KVO，各控件设初始值
        [self removeObserverAndNotification];
        [self initialControls];

        [self upDateData];
        _currentUrl = _detailModel.content.voice.url;

    }
}

- (void)upDateData {
    
    
    [_backImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://qn.zheli.io/%@", _detailModel.content.avatar]]];
    _nameLabel.text = _detailModel.content.uname;
    [_rotatingView.imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://qn.zheli.io/%@",  _detailModel.content.avatar]]];

    [_rotatingView resumeLayer];
    
    NSURL *voiceUrl = [NSURL URLWithString:[NSString stringWithFormat:@"http://qn.zheli.io/%@", _detailModel.content.voice.url]];
    playerItem = [AVPlayerItem playerItemWithURL: voiceUrl];
    [playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];// 监听status属性

    [self.player replaceCurrentItemWithPlayerItem:playerItem];
    [self.player play];
    [self addEndTimeNotification];

    _isPlaying = YES;

    

    [self monitoringPlaying:playerItem];
//    [self.rotatingView removeAnimation];

    
    
}

- (void)monitoringPlaying:(AVPlayerItem *)item {
    __weak typeof (self) weakSelf = self;
    self.playTimeObserver = [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 30) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        // 计算当前在第几秒
        float currentPlayTime = (double)item.currentTime.value/item.currentTime.timescale;
        [weakSelf updateVideoSlider:currentPlayTime];

    }];
}

-(void)addEndTimeNotification{
    //给AVPlayerItem添加播放完成通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}

-(void)playbackFinished:(NSNotification *)notification{
    NSLog(@"视频播放完成.");
    playerItem = [notification object];
    [playerItem seekToTime:kCMTimeZero];
    [self.player play];
//    if (_playerMode == AudioPlayerModeSinglePlay) {
//        playerItem = [notification object];
//        [playerItem seekToTime:kCMTimeZero];
//        [self.player play];
//    }else{
//        [self nextIndexAdd];
//        [self updateAudioPlayer];
//    }
}


- (void)updateVideoSlider:(float)currentTime{
//    [self setLockViewWith:_playingModel currentTime:currentTime];
    self.slider.value = currentTime;
    self.playingTimeLabel.text = [NSString convertTime:currentTime];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    AVPlayerItem *item = (AVPlayerItem *)object;
    if ([keyPath isEqualToString:@"status"]) {
        if ([playerItem status] == AVPlayerStatusReadyToPlay) {
            NSLog(@"AVPlayerStatusReadyToPlay");
            CMTime duration = item.duration;// 获取视频总长度
            [self setMaxDuratuin:CMTimeGetSeconds(duration)];
//            [self play];
        }else if([playerItem status] == AVPlayerStatusFailed) {
            NSLog(@"AVPlayerStatusFailed");
//            [self stop];
        }
    }
}
- (void)setMaxDuratuin:(float)duration{
    _totalTime = duration;
    self.slider.maximumValue = duration;
    self.maxTimeLabel.text = [NSString convertTime:duration];
}

- (void)initialControls{
//    [self stop];
//    self.playingTime.text = @"00:00";
    self.slider.value = 0.0f;
    [self.pauseButton setImage:[UIImage imageNamed:@"player_btn_pause_normal.jpg"] forState:UIControlStateNormal];
    if (_isPlaying == YES) {
        NSLog(@"正在播放");

    } else {
        NSLog(@"停止播放");
        [self.pauseButton removeTarget:self action:@selector(playMusic:) forControlEvents:UIControlEventTouchUpInside];
        [self.pauseButton addTarget:self action:@selector(pauseMusic:) forControlEvents:UIControlEventTouchUpInside];

    }
    
    
//    [self.rotatingView removeAnimation];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self createView];
    [_rotatingView addAnimation];

}


- (void)createView {
    
    // 毛玻璃
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
    UIVisualEffectView *visualView = [[UIVisualEffectView alloc]initWithEffect:blurEffect];
    visualView.alpha = 1;
    visualView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    [_backImageView addSubview:visualView];
    
    
    // 旋转图
    self.rotatingView = [[VoicePlayerRotatingView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH / 5 * 4, SCREEN_WIDTH / 5 * 4)];
    _rotatingView.center = CGPointMake(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 - 50);
    _rotatingView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_rotatingView];
    _rotatingView.layer.cornerRadius = SCREEN_WIDTH / 5 * 4 / 2;
    _rotatingView.layer.masksToBounds = YES;
    _rotatingView.layer.borderColor = [UIColor grayColor].CGColor;
    _rotatingView.layer.borderWidth = 3;

    
    [self.slider setMinimumTrackImage:[UIImage imageNamed:@"player_slider_playback_left"] forState:UIControlStateNormal];
    [self.slider setMaximumTrackImage:[UIImage imageNamed:@"player_slider_playback_right"] forState:UIControlStateNormal];
    [self.slider setThumbImage:[UIImage imageNamed:@"player_slider_playback_thumb"] forState:UIControlStateNormal];
    [self.slider addTarget:self action:@selector(changeTime:) forControlEvents:UIControlEventValueChanged];
    
//    [self.pauseButton addTarget:self action:@selector(pauseMusic:) forControlEvents:UIControlEventTouchUpInside];

   
}

- (void)pauseMusic:(UIButton *)pauseButton {
    NSLog(@"点击暂停按钮");
    [self.player pause];
    [self.rotatingView pauseLayer];
    [pauseButton setImage:[UIImage imageNamed:@"player_btn_play_normal.jpg"] forState:UIControlStateNormal];
    [pauseButton removeTarget:self action:@selector(pauseMusic:) forControlEvents:UIControlEventTouchUpInside];
    [pauseButton addTarget:self action:@selector(playMusic:) forControlEvents:UIControlEventTouchUpInside];
    _isPlaying = NO;
}


- (void)playMusic:(UIButton *)playButton {
    NSLog(@"点击播放按钮");
    [self.player play];
    [self.rotatingView resumeLayer];
    [playButton setImage:[UIImage imageNamed:@"player_btn_pause_normal.jpg"] forState:UIControlStateNormal];
    [playButton removeTarget:self action:@selector(playMusic:) forControlEvents:UIControlEventTouchUpInside];
    [playButton addTarget:self action:@selector(pauseMusic:) forControlEvents:UIControlEventTouchUpInside];
    _isPlaying = YES;
}


- (void)changeTime:(UISlider *)slider {
    //转换成CMTime才能给player来控制播放进度
    CMTime dragedCMTime = CMTimeMake(self.slider.value, 1);
    [playerItem seekToTime:dragedCMTime];
}

- (void)removeObserverAndNotification{
    [self.player replaceCurrentItemWithPlayerItem:nil];
    [self.player removeTimeObserver:_playTimeObserver];
    [playerItem removeObserver:self forKeyPath:@"status"];
    playerItem = nil;
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}


- (IBAction)popBack:(id)sender {
    [self dismissViewControllerAnimated:YES completion:^{
        
        
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
